<template>
  <div>
    <!-- action="http://example-chongqing.oss-cn-beijing.aliyuncs.com" -->
    <el-upload
      action="http://ldsw-wx.oss-cn-beijing.aliyuncs.com"
      :data="dataObj"
      :limit="flag === 0 ? 9 : flag"
      :on-exceed="showExceed"
      list-type="picture-card"
      :file-list="fileList"
      :on-remove="toRemove"
      ref="upload"
      :multiple="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :on-error="handleError"
    >
      <!-- :on-change="pushFile" -->
      <i slot="default" class="el-icon-plus"></i>

      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="checkPictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="toRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="pictureVisible">
      <img width="100%" :src="pictureImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { getSignature } from "@/api/qiniu";
export default {
  name: "uploadImage",
  props: {
    value: {
      type: String,
      default: "",
    },
    flag: {
      type: Number,
      default: 0,
    },
    closed: {
      type: Boolean,
      default: false,
    },
    update: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    value(newval, oldval) {
      // console.log(newval);
      // console.log(oldval);
      if (newval == "0") {
        newval = "";
      }
      this.Cover = newval;
      console.log(this.Cover);
      if (!oldval) {
        if (this.closed === true) return;
        this.getCoverList();
      }
    },
  },
  data() {
    return {
      fileList: [],
      imageUrl: "",
      pictureImageUrl: "",
      pictureVisible: false,
      disabled: false,
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
      },
      coverData: [],
      Cover: this.value,
      count: 0,
    };
  },
  created() {
    // this.fileList = this.Cover;
    // console.log(this.coverData);
    // console.log(this.fileList);
  },
  methods: {
    emitInput(val) {
      this.$emit("input", val);
    },
    // 限制上传图片张数
    showExceed(files, fileList) {
      if (this.flag === 0)
        return this.$message.warning(
          `当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        );
      return this.$message.warning(
        `当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 上传之前事件
    beforeAvatarUpload(file) {
      console.log(file);
      // console.log(res);
      return new Promise((resolve, reject) => {
        // console.log(reject);
        // console.log(this.dataObj);
        getSignature({ road: "one" }).then((res) => {
          // console.log(res);
          var timestamp=new Date().getTime()
          console.log(timestamp)
          var fileExtension = file.name.substring(file.name.lastIndexOf('.'));
          console.log(fileExtension)
          this.dataObj.policy = res.result.policy;
          this.dataObj.signature = res.result.signature;
          this.dataObj.ossaccessKeyId = res.result.accessid;
          this.dataObj.dir = res.result.dir;
          this.dataObj.host = res.result.host;
          this.dataObj.key = res.result.dir + timestamp + fileExtension;
          resolve(true);
        });
      });
    },
    // 成功后的事件
    handleAvatarSuccess(res, file) {
      let imgUrl = this.dataObj.host + "/" + this.dataObj.key;
      console.log(this.Cover);
      console.log(this.update);
      if (this.update) {
        this.imageUrl += this.Cover + imgUrl + "#";
      } else {
        this.imageUrl += imgUrl + "#";
      }
      console.log(this.imageUrl);
      this.emitInput(this.imageUrl);
      // this.fileList.push(file);
      console.log(this.fileList);
      this.$message.success("上传成功！");
    },
    // 失败后的事件
    handleError() {
      this.$message.error("上传失败！");
    },
    // 移除照片
    toRemove(file, fileList) {
      // let self = this;
      if (file && file.status === "success") {
        let fileList = this.$refs.upload.uploadFiles;
        // console.log(fileList);
        let index = fileList.findIndex((fileItem) => {
          return fileItem.uid === file.uid;
        });
        // console.log(index);
        fileList.splice(index, 1);
        console.log(fileList);
        let url = "";
        fileList.map((item) => {
          console.log(item);
          url += item.url + "#";
        });
        // console.log(url);
        this.imageUrl = url;
        this.emitInput(this.imageUrl);
        this.fileList = fileList;
        this.coverData = fileList;
        // console.log(this.coverData);
        // console.log(this.fileList);
      }
    },
    // Preview事件
    checkPictureCardPreview(file) {
      let self = this;
      self.pictureImageUrl = file.url;
      self.pictureVisible = true;
    },
    getCoverList() {
      let self = this;
      if (self.Cover.includes(",")) {
        console.log(1);
        let data = self.Cover.split(",");
        console.log(data);
        for (let url of data) {
          if (url) {
            self.coverData.push({ url });
          }
        }
        self.fileList = self.coverData;
      } else {
        console.log(2);
        let data = self.Cover.split("#");
        console.log(data);
        for (let url of data) {
          if (url) {
            self.coverData.push({ url });
          }
        }
        self.fileList = self.coverData;
      }
      // else if (!self.Cover.includes(",") && !self.Cover.includes("#")) {
      //   self.fileList.push({ url: self.Cover });
      //   console.log(self.Cover);
      // }
      // 去重
      // const res = new Map();
      // self.fileList = self.coverData.filter((arr) => {
      //   return !res.has(arr.id) && res.set(arr.id, 1);
      // });
    },
  },
};
</script>

<style lang="sass" scoped>
</style>